# _*_ coding:utf-8 _*_
# This is a sample Python script.

# Press Shift+F10 to execute it or replace it with your code.
# Press Double Shift to search everywhere for classes, files, tool windows, actions, and settings.
import shutil
import time
import webbrowser
from selenium import webdriver
from time import sleep
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.chrome.options import Options
import subprocess
from selenium.webdriver.common.keys import Keys
import math
import os

from config.global_settings import FPDK_URL, jsp_password
from utils import json_utils
from pywinauto import keyboard
from utils import log_utils

# from PIL import Image
#
from utils.ocr_util import invoice_util

H = 39
# 需要下载的文件格式
# FILE_TYPES = ['.doc', '.docx', '.pdf', '.xls', 'xlsx']
# # 文件下载目录
# PATH = r'C:\Users\admin\Desktop\download'
# # 数据文件目录
# DATA_PATH = r"F:\python_project\OAContractDrawFill\settings\data.json"
# # 浏览器位置
# CHROME_PATH = r'C:\Program Files\Google\Chrome\Application\chrome.exe'
# # 驱动目录
# DRIVER_PATH = r'F:\python_project\OAContractDrawFill'

FILE_TYPES = ''
PATH = ''
DATA_PATH = ''
CHROME_PATH = ''
DRIVER_PATH = ''
USER_NAME = ''
PASSWORD = ''
LAW_USER_NAME = ''
LAW_PASSWORD = ''
logger = ''


def del_file(path):
    ls = os.listdir(path)
    for i in ls:
        c_path = os.path.join(path, i)
        if os.path.isdir(c_path):
            del_file(c_path)
        else:
            os.remove(c_path)


def find_element_by_xpath(xpath='', chromeBrowser=''):
    try:
        elem = chromeBrowser.find_element_by_xpath(xpath)
        return elem
    except Exception as e:
        print(e)
        logger.error("未找到xpath:" + xpath)
        return False


def find_elements_by_xpath(xpath='', chromeBrowser=''):
    try:
        elems = chromeBrowser.find_element_by_xpath(xpath)
        return elems
    except Exception as e:
        logger.error(e)
        logger.error("未找到xpath:" + xpath)
        return []


def get_element_by_xpath(xpath='', chromeBrowser=''):
    try:
        elem = chromeBrowser.find_element_by_xpath(xpath)
        return elem
    except Exception as e:
        return None


def run():
    webbrowser.register('chrome', None, webbrowser.BackgroundBrowser(CHROME_PATH))
    chromeOptions = webdriver.ChromeOptions()
    prefs = {"download.default_directory": PATH}
    chromeOptions.add_experimental_option("prefs", prefs)
    chromeBrowser = webdriver.Chrome(chrome_options=chromeOptions)
    # 登录
    login(chromeBrowser)

    # 关闭知道了弹出框
    time.sleep(4)
    find_element_by_xpath('//div[@class="text-center"]/a[@onclick="closehzfp();"]', chromeBrowser).click()

    time.sleep(0.5)
    find_element_by_xpath('//a[text()="抵扣勾选"]', chromeBrowser).click()
    time.sleep(0.5)
    find_element_by_xpath('//a[text()="发票抵扣勾选"]', chromeBrowser).click()
    # 鼠标移动到发票号码输入框
    time.sleep(1)
    element = find_element_by_xpath('//input[@id="fphm"]', chromeBrowser)
    ActionChains(chromeBrowser).move_to_element(element).perform()
    logger.info('开始发票抵扣！')
    # 读取指定文件夹下的所有发票
    identify = ["查无此票", "已抵扣", "发票存在问题"]
    filePath = SOURCE_PATH

    for a, b, c in os.walk(filePath):
        for i in range(len(c)):
            fp_path = os.path.join(filePath, c[i])
            # 判断是否是处理过的票
            is_contain = judge_identify(c[i],identify)
            if not is_contain:
                result = invoice_util(fp_path)
                if '' != result.get('number'):
                    fpdk(chromeBrowser, result, c[i],fp_path)
                else:
                    logger.info('OCR识别发票信息数据为空！')
    logger.info('结束发票抵扣！')
    time.sleep(1)
    # 发票抵扣完成关闭浏览器
    chromeBrowser.quit()


def login(chromeBrowser=''):
    logger.info('开始登录')

    # chrome  参数查询  chrome://version/
    url = FPDK_URL

    chromeBrowser.get(url)
    chromeBrowser.maximize_window()
    # 你的连接不是私密连接

    try:
        find_element_by_xpath('//button[@id="details-button"]', chromeBrowser).click()
        time.sleep(0.5)
        find_element_by_xpath('//a[@id="proceed-link"]', chromeBrowser).click()
    except:
        ...

    time.sleep(1)
    # 可能弹出升级内容说明
    try:
        find_element_by_xpath('//a[@id="okButton"]', chromeBrowser).click()
    except:
        ...

    time.sleep(1)

    ele = find_element_by_xpath('//input[@id="password1"]', chromeBrowser)
    ActionChains(chromeBrowser).click(ele).send_keys('12345678').perform()
    time.sleep(1)

    find_element_by_xpath('//input[@id="submit"]', chromeBrowser).click()

    logger.info('登录成功')


def comare_invoice_info(fpxx, result):
    date = result.get('date').replace("年", "-").replace("月", "-").replace("日", "")
    if (fpxx.get('fpdm') == result.get('code') and
            fpxx.get('fphm') == result.get('number') and
            fpxx.get('kprq') == date and
            fpxx.get('xfmc') == result.get('seller') and
            fpxx.get('je') == result.get('pretax_amount') and
            fpxx.get('se') == result.get('tax') and
            "正常" == fpxx.get('fpzt') and
            "否" == fpxx.get('sfgx') and
            "正常" == fpxx.get('glzt')):
        return True
    else:
        return False


def judge_identify(invoiceName='', identify=[]):
    is_contain = False
    for i in range(len(identify)):
        if (identify[i] in invoiceName):
            is_contain = True
    return is_contain

def move_file(file_path=''):
    # 获取当前日期
    # print(datetime.today())
    now = time.localtime()
    # now_time = time.strftime("%Y-%m-%d %H:%M:%S", now)
    now_time = time.strftime("%Y-%m-%d", now)
    # 创建文件夹
    dstpath = os.path.join(ROOT_PATH, now_time)

    # 判断文件是否存在
    if not os.path.isfile(file_path):
        logger.error("%s not exist!" % (file_path))
    else:
        fpath, fname = os.path.split(file_path)  # 分离文件名和路径
        if not os.path.exists(dstpath):
            os.makedirs(dstpath)  # 创建路径
        shutil.move(file_path, os.path.join(dstpath, fname))  # 移动文件
        # print("move %s -> %s" % (file_path, dstpath + fname))


def fpdk(chromeBrowser='', result='', name='',fp_path=''):
    time.sleep(1)
    # 输入发票号码
    find_element_by_xpath('//input[@id="fphm"]', chromeBrowser).clear()
    time.sleep(0.5)
    find_element_by_xpath('//input[@id="fphm"]', chromeBrowser).send_keys(result.get('number'))
    time.sleep(1)
    # 开票日期
    find_element_by_xpath('//input[@id="sjq"]', chromeBrowser).clear()
    time.sleep(0.5)
    date = result.get('date').replace("年", "-").replace("月", "-").replace("日", "")
    find_element_by_xpath('//input[@id="sjq"]', chromeBrowser).send_keys(date)
    time.sleep(0.5)
    # 点击查询
    find_element_by_xpath('//a[@id="search"]', chromeBrowser).click()

    # 判断是否查询到发票信息
    time.sleep(1)
    ele = get_element_by_xpath('//div[@id="popup_message"]', chromeBrowser)
    if ele is not None:
        find_element_by_xpath('//input[@id="popup_ok"]', chromeBrowser).click()
        # 修改文件名称
        os.chdir(SOURCE_PATH)
        new_name = "查无此票" + name
        os.rename(name, new_name)
        os.chdir(DRIVER_PATH)
    else:
        # 判断发票信息
        tr_path = '//table[@id="example"]/tbody/tr'
        fpxx = {}
        for i in range(1, 15):
            td = find_element_by_xpath(f"{tr_path}/td[{i}]", chromeBrowser)
            if i == 2:
                # 发票代码
                fpxx['fpdm'] = td.get_attribute('textContent')
            elif i == 3:
                # 发票号码
                fpxx['fphm'] = td.get_attribute('textContent')
            elif i == 4:
                # 开票日期
                fpxx['kprq'] = td.get_attribute('textContent')
            elif i == 5:
                # 销方名称
                fpxx['xfmc'] = td.get_attribute('textContent')
            elif i == 6:
                # 金额
                fpxx['je'] = td.get_attribute('textContent')
            elif i == 7:
                # 税额
                fpxx['se'] = td.get_attribute('textContent')
            elif i == 9:
                # 发票状态
                fpxx['fpzt'] = td.get_attribute('textContent')
            elif i == 10:
                # 发票类型
                fpxx['fplx'] = td.get_attribute('textContent')
            elif i == 12:
                # 是否勾选
                fpxx['sfgx'] = td.get_attribute('textContent')
            elif i == 14:
                # 管理状态
                td = find_element_by_xpath(f"{tr_path}/td[{i}]/span", chromeBrowser)
                fpxx['glzt'] = td.get_attribute('textContent')
        # 比较查询到的发票信息和识别出的发票信息
        compare_result = comare_invoice_info(fpxx, result)
        if compare_result:
            # 勾选
            time.sleep(0.5)
            find_element_by_xpath('//input[@id="a1"]', chromeBrowser).click()

            # 提交
            time.sleep(0.5)
            find_element_by_xpath('//a[@id="sub"]', chromeBrowser).click()

            # 点击确认
            time.sleep(0.5)
            # find_element_by_xpath('//input[@id="popup_ok"]', chromeBrowser).click()
            # 点击取消
            find_element_by_xpath('//input[@id="popup_cancel"]', chromeBrowser).click()
            # 修改文件名称
            os.chdir(SOURCE_PATH)
            # new_name = "已抵扣" + name
            # os.rename(name, new_name)
            # 移动文件到指定文件夹
            move_file(fp_path)
            os.chdir(DRIVER_PATH)
        else:
            # 修改文件名称
            os.chdir(SOURCE_PATH)
            new_name = "发票存在问题" + name
            os.rename(name, new_name)
            os.chdir(DRIVER_PATH)


if __name__ == '__main__':
    config = json_utils.get_json_by_path(r'D:\workspace\PycharmWorkSpace\PayAndReceiveAccounts\config\config.json')
    LOG_DIR = config['LOG_DIR']
    LOG_NAME = config['LOG_NAME']
    log_utils.create_log_file(LOG_DIR)
    logger = log_utils.Logger(LOG_DIR + "\\" + LOG_NAME).logger
    FILE_TYPES = config['FILE_TYPES']
    PATH = config['PATH']
    DATA_PATH = config['DATA_PATH']
    CHROME_PATH = config['CHROME_PATH']
    DRIVER_PATH = config['DRIVER_PATH']
    ROOT_PATH = config['ROOT_PATH']
    SOURCE_PATH = config['SOURCE_PATH']
    run()
    # 读取指定文件夹下的所有发票
    # filePath = "D:\\test"
    # for a, b, c in os.walk(filePath):
    #     for i in range(len(c)):
    #         fp_path = os.path.join(filePath,c[i])
    #         # print(fp_path)
    #         result = invoice_util(fp_path)
    #         print(result.get('seller'))
